import Json from '@/data/ResultJson'
import { AutoId } from '@/data/AutoId'
const categoryList = [
  { id: 1, name: '小说' },
  { id: 2, name: '动漫' },
  { id: 3, name: '玄幻' }
]
function getIndexById (id) {
  id = parseInt(id)
  let index = -1
  for (let i = 0; i < categoryList.length; i++) {
    if (categoryList[i].id === id) {
      index = i
      break
    }
  }
  if (index === -1) {
    return Json.error('编号异常！')
  }
  return index
}

export function getCategoryListAjax (searchInfo = {}) {
  let dataList = categoryList.filter(item => item.name === searchInfo.name || !searchInfo.name)
  dataList = dataList.reverse()
  return Json.success(dataList)
}

export function deleteCategoryAjax (id) {
  const index = getIndexById(id)
  categoryList.splice(index, 1)
  return Json.success()
}

export function getCategoryByIdAjax (id) {
  const index = getIndexById(id)
  return Json.success({ ...categoryList[index] })
}

export function saveOrUpdate (formData = {}) {
  if (formData.id) {
    const index = getIndexById(formData.id)
    categoryList[index] = { ...formData }
  } else {
    for (const category of categoryList) {
      if (category.name === formData.name) {
        return Json.error('分类名已存在')
      }
    }
    formData.id = AutoId.categoryId
    categoryList.push(formData)
    AutoId.categoryId++
  }
  return Json.success()
}
